<template>
  <div>
    <el-form
      ref="firstForm"
      :model="formData"
      label-width="1.3125rem"
      :rules="rules"
      class="flex flex-wrap pr-10 open-form help-box"
    >
      <el-form-item :label="$t('SERVICE_NAME')" prop="bizName" class="w-50">
        <el-input v-model.trim="formData.bizName" maxlength="50" />
      </el-form-item>
      <el-form-item :label="$t('SERVICE_CODE')" class="w-50 relative">
        <el-input v-model="formData.resourceCode" maxlength="32" />
        <el-popover width="200" trigger="hover" class="form-tips">
          <div class="text-color" v-html="$t('SERVICE_CODE_TIPS')" />
          <i slot="reference" class="iconfont icon-AFSwenhao text-color ml-5" />
        </el-popover>
      </el-form-item>
      <!-- a端站点 -->
      <el-form-item
        :label="$t('A_END_STATION_NAME')"
        prop="aStationId"
        class="w-50"
      >
        <el-input v-model="formData.aStationId" class="hide" />
        <region-cascader
          class="block"
          :selected-ids="[formData.aStationId]"
          :clearable="false"
          data-name="stationTree"
          :placeholder="'A_END_STATION_NAME'"
          @change="aStationChange"
        />
      </el-form-item>
      <!-- z端站点 -->
      <el-form-item
        :label="$t('Z_END_STATION_NAME')"
        prop="zStationId"
        class="w-50"
      >
        <el-input v-model="formData.zStationId" class="hide" />
        <region-cascader
          class="block"
          :selected-ids="[formData.zStationId]"
          :clearable="false"
          data-name="stationTree"
          :placeholder="'Z_END_STATION_NAME'"
          @change="zStationChange"
        />
      </el-form-item>
      <!-- a端节点 -->
      <el-form-item :label="$t('ANODE')" class="w-50" prop="aNodeId">
        <el-select
          v-model="formData.aNodeId"
          :placeholder="$t('SELECT_ANODE')"
          clearable
        >
          <el-option
            v-for="item in aNodeList"
            :key="item.nodeId"
            :value="item.nodeId"
            :label="item.nodeName"
          />
        </el-select>
      </el-form-item>
      <!-- z端节点 -->
      <el-form-item :label="$t('ZNODE')" class="w-50" prop="zNodeId">
        <el-select
          v-model="formData.zNodeId"
          :placeholder="$t('SELECT_ZNODE')"
          clearable
        >
          <el-option
            v-for="item in zNodeList"
            :key="item.nodeId"
            :value="item.nodeId"
            :label="item.nodeName"
          />
        </el-select>
      </el-form-item>
      <!-- a端节点端口 -->
      <el-form-item :label="$t('A_END_NODE_PORT')" class="w-50" prop="aPortId">
        <el-select
          v-model="formData.aPortId"
          class="inline-block"
          style="width: calc(100% - 100px)"
          :placeholder="$t('SELECT_PORT')"
          clearable
        >
          <el-option
            v-for="item in getEnAblePortList(aPortList)"
            :key="item.portId"
            :disabled="setPortDisabled(item, 'z')"
            :value="item.portId"
            :label="item.bizName"
          />
        </el-select>
        <el-select
          v-model="formData.aPortData.funcType"
          style="width: 100px"
          class="inline-block"
          disabled
          placeholder=""
        >
          <el-option
            v-for="item in directionList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- z端节点端口 -->
      <el-form-item :label="$t('Z_END_NODE_PORT')" class="w-50" prop="zPortId">
        <el-select
          v-model="formData.zPortId"
          style="width: calc(100% - 100px)"
          class="inline-block"
          clearable
          :placeholder="$t('SELECT_PORT')"
        >
          <el-option
            v-for="item in getEnAblePortList(zPortList)"
            :key="item.portId"
            :disabled="setPortDisabled(item, 'a')"
            :value="item.portId"
            :label="item.bizName"
          />
        </el-select>
        <el-select
          v-model="formData.zPortData.funcType"
          style="width: 100px"
          class="inline-block"
          disabled
          placeholder=""
        >
          <el-option
            v-for="item in directionList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <template
        v-if="!!formData.aPortData2.portId || !!formData.zPortData2.portId"
      >
        <!-- 双芯显示 -->
        <el-form-item label="" class="w-50">
          <el-select
            v-model="formData.aPortData2.portId"
            class="inline-block"
            style="width: calc(100% - 100px)"
            disabled
            placeholder=""
          >
            <el-option
              v-for="item in aPortList"
              :key="item.portId"
              :value="item.portId"
              :label="item.bizName"
            />
          </el-select>
          <el-select
            v-model="formData.aPortData2.funcType"
            style="width: 100px"
            class="inline-block"
            disabled
            placeholder=""
          >
            <el-option
              v-for="item in directionList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" class="w-50">
          <el-select
            v-model="formData.zPortData2.portId"
            style="width: calc(100% - 100px)"
            class="inline-block"
            disabled
            placeholder=""
          >
            <el-option
              v-for="item in zPortList"
              :key="item.portId"
              :value="item.portId"
              :label="item.bizName"
            />
          </el-select>
          <el-select
            v-model="formData.zPortData2.funcType"
            style="width: 100px"
            class="inline-block"
            disabled
            placeholder=""
          >
            <el-option
              v-for="item in directionList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
      </template>
      <!-- a端连接设备 -->
      <el-form-item :label="$t('A_END_CONNECT_DEVICE')" class="w-50">
        <el-input v-model="aAfsData.nodeName" maxlength="32" disabled />
      </el-form-item>
      <!-- z端连接设备 -->
      <el-form-item :label="$t('Z_END_CONNECT_DEVICE')" class="w-50">
        <el-input v-model="zAfsData.nodeName" maxlength="32" disabled />
      </el-form-item>
      <!-- 业务等级 -->
      <el-form-item :label="$t('BIZ_LEVEL')" class="w-50 relative" required>
        <el-select v-model="formData.bizLevel">
          <el-option
            v-for="item in dictList.BIZ_LEVEL"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
        <el-popover width="200" trigger="hover" class="form-tips">
          <div class="text-color" v-html="$t('BIZ_LEVEL_TIPS')" />
          <i slot="reference" class="iconfont icon-AFSwenhao text-color ml-5" />
        </el-popover>
      </el-form-item>
      <div class="w-50" />
    </el-form>
    <FilterItem ref="filterItem" :form-data="formData" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import nodeApi from '@/api/oen/NodeApi'
  import segmentChannelApi from '@/api/oen/SegmentChannelApi'
  import RegionCascader from '@/components/RegionCascader'
  import FilterItem from './FilterItem'

  export default {
    components: { RegionCascader, FilterItem },
    props: {
      reOpenData: {
        type: Object,
        default: () => {}
      },
      formData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        aNodeList: [],
        zNodeList: [],
        aPortList: [],
        zPortList: [],
        aAfsData: {},
        zAfsData: {}
      }
    },
    computed: {
      ...mapGetters(['dictList']),
      rules() {
        return {
          bizName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('SERVICE_NAME'),
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                const reg = /[~%&<>\[\]\{\}=_+]/g
                if (value && reg.test(value)) {
                  callback(new Error(this.$t('CHARACTERS_SUGGEST', { msg: '~%&<>[]{}=_+' })))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            }
          ],
          aStationId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('A_END_STATION_NAME'),
              trigger: 'change'
            }
          ],
          zStationId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('Z_END_STATION_NAME'),
              trigger: 'change'
            }
          ],
          aNodeId: [
            {
              required: true,
              message: this.$t('SELECT_ANODE'),
              trigger: 'change'
            }
          ],
          zNodeId: [
            {
              required: true,
              message: this.$t('SELECT_ZNODE'),
              trigger: 'change'
            }
          ],
          aPortId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('A_END_NODE_PORT'),
              trigger: 'change'
            }
          ],
          zPortId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('Z_END_NODE_PORT'),
              trigger: 'change'
            }
          ]
        }
      },
      directionList() {
        const doubleList = [
          { value: 'RECEIVE', label: this.$t('RECEIVE') },
          { value: 'SEND', label: this.$t('SEND') },
          { value: 'SEND_RECEIVE', label: this.$t('SEND_RECEIVE') }
        ]
        return doubleList
      }
    },
    watch: {
      'formData.aNodeId': function(newVal) {
        this.formData.aNodeData = !newVal
          ? {}
          : this.aNodeList.find(i => i.nodeId === newVal)
        this.getPortList(this.formData.aNodeData, 'a')
      },
      'formData.zNodeId': function(newVal) {
        this.formData.zNodeData = !newVal
          ? {}
          : this.zNodeList.find(i => i.nodeId === newVal)
        this.getPortList(this.formData.zNodeData, 'z')
      },
      // 根据az端口类型判断是否显示double，single类型默认收发
      'formData.aPortId': function(newVal) {
        this.portChange(newVal, 'a')
      },
      // 根据az端口类型判断是否显示double，single类型默认收发
      'formData.zPortId': function(newVal) {
        this.portChange(newVal, 'z')
      }
    },
    methods: {
      // 筛选可选择状态的端口列表
      getEnAblePortList(data) {
        return data.filter(i => i.status === 'CONN')
      },
      // 选中端口更改事件
      portChange(newVal, side) {
        const portData = !newVal
          ? {}
          : this[side + 'PortList'].find(i => i.portId === newVal)
        // console.log('portData', portData)
        if (portData.interfaceType === 'DOUBLE') {
          this.formData[side + 'PortData2'] = this[side + 'PortList'].find(
            i => i.portId === portData.doublePortId
          )
        } else {
          this.formData[side + 'PortData2'] = {}
        }

        this.formData[side + 'PortData'] = portData
        this[side + 'AfsData'] = {}
        newVal && this.getAfsData(side)
      },
      // 获取选择端口连接的afs设备
      getAfsData(side) {
        segmentChannelApi
          .connNode({ portId: this.formData[side + 'PortId'] })
          .then(res => {
            this[side + 'AfsData'] = res || {}
          })
      },
      // 根据已选择的az端口设置未选择的az端口是否可选
      setPortDisabled(item, side) {
        const contrastData = this.formData[side + 'PortData']
        if (contrastData.portId) {
          if (contrastData.interfaceType === 'DOUBLE') {
            return (
              item.interfaceType === 'SINGLE' ||
              item.funcType === contrastData.funcType
            )
          } else {
            return item.interfaceType !== contrastData.interfaceType
          }
        } else {
          return false
        }
      },
      // 获取端口列表
      getPortList(data, side) {
        this.formData[side + 'PortId'] = ''
        this.formData[side + 'PortList'] = []
        // console.log('getPortList', data)
        if (Object.keys(data).length === 0) return
        // 传输设备通过选择的节点获取节点下端口信息
        let nodePorts = []
        if (data.nodeCategory === 'TRANSPORT') {
          const shelfList = data.properties.trans.shelfList
          shelfList.forEach(i => {
            i.slotList.forEach(j => {
              j.netPortList.forEach(z => {
                if (z.isInsert) {
                  // 双芯端口添加配对端口id
                  if (z.interfaceType === 'DOUBLE') {
                    z.litPortList[0].interfaceType = z.interfaceType
                    z.litPortList[0].doublePortId = z.litPortList[1].portId
                    z.litPortList[1].doublePortId = z.litPortList[0].portId
                    z.litPortList[1].interfaceType = z.interfaceType
                  } else {
                    z.litPortList[0].interfaceType = z.interfaceType
                    z.litPortList[0].doublePortId = ''
                  }
                  nodePorts = [...nodePorts, ...z.litPortList]
                }
              })
            })
          })
        }
        // console.log('nodePorts', nodePorts)

        // 通过接口获取节点列表(节点名称等信息)
        nodeApi
          .portList({
            nodeId: data.nodeId,
            status: null
          })
          .then(res => {
            res = res || []
            // 筛选未开通业务的设备端口 只能选择（成端）
            // res = res.filter(i => i.status === 'CONN')
            // 光分器只能选择输入
            if (data.nodeCategory === 'LIGHT_SPLIT') {
              res[0].interfaceType = 'SINGLE'
              res[0].funcType = 'SEND_RECEIVE'
              res[0].bizName = this.$utils.handleServiceI18n(res[0].bizName)
              res = [res[0]]
            } else {
              // 传输设备信息合并
              res = res.map(i => {
                const nodePortData = nodePorts.find(j => j.portId === i.portId)
                return nodePortData ? { ...i, ...nodePortData } : { ...i }
              })
            }
            this[side + 'PortList'] = res

            // 重新开通设置选中端口,优先校验端口信息是否存在
            this.$nextTick(() => {
              if (this.reOpenData.bizChannelList) {
                const portSide = side === 'a' ? 'startPortId' : 'endPortId'
                const channelData = this.reOpenData.bizChannelList[0]
                if (this.getEnAblePortList(res).some(i =>
                  i.portId === channelData[portSide])) {
                  this.formData[side + 'PortId'] = channelData[portSide]
                } else {
                  this.$message.closeAll()
                  this.$message.error(this.$t(`${side.toUpperCase()}_END_NODE_PORT`) +
                    '：' + this.$t('BEEN_USED'))
                }
                channelData[portSide] = null
                if (!channelData.startPortId && !channelData.endPortId) {
                  this.reOpenData.bizChannelList = null
                }
              }
            })
          })
      },
      // a站点改变
      aStationChange(data) {
        this.aNodeList = []
        this.formData.aPortData = { funcType: '' }
        this.aPortList = []
        if (this.formData.aStationId !== data) {
          this.formData.aStationId = data
          this.formData.aNodeId = ''
          this.formData.aPortId = ''
          data && this.getNodeList(data, 'a')
        }
      },
      // z站点改变
      zStationChange(data) {
        this.zNodeList = []
        this.formData.zPortData = { funcType: '' }
        this.zPortList = []
        if (this.formData.zStationId !== data) {
          this.formData.zStationId = data
          this.formData.zNodeId = ''
          this.formData.zPortId = ''
          data && this.getNodeList(data, 'z')
        }
      },
      // 获取站点下节点
      getNodeList(stationId, side) {
        nodeApi.queryList({ stationIdList: [stationId] }).then(res => {
          // 节点只能选择传输设备和光分
          res = res.filter(
            i =>
              i.nodeCategory === 'TRANSPORT' || i.nodeCategory === 'LIGHT_SPLIT'
          )
          this[side + 'NodeList'] = res || []
          // 重新开通设置选中站点,优先校验节点信息是否存在
          const nodeSide = side === 'a' ? 'startNode' : 'endNode'
          this.$nextTick(() => {
            if (this.reOpenData[nodeSide + 'Id']) {
              if (res.some(i => i.nodeId === this.reOpenData[nodeSide + 'Id'])) {
                this.formData[side + 'NodeId'] = this.reOpenData[nodeSide + 'Id']
              } else {
                this.reOpenData.bizChannelList = null
                this.$message.closeAll()
                this.$message.error(this.reOpenData[nodeSide].nodeName +
                  '：' + this.$t('NODE_ERROR'))
              }
              this.reOpenData[nodeSide + 'Id'] = null
            }
          })
        })
      }
    }
  }
</script>

